
import {baseUrl} from './utils/commons.js';

// var baseUrl =baseUrl
// var baseUrl ='https://t3.lemon-e.cn/'
var apiKey=''

var request={
  /** 请求基类方法*/
  baseRequest: function (url, method, param, success, fail, complete) {
    console.log('entry')
    if (wx.canIUse('showLoading')) {
      wx.showLoading({ title: '加载中' })
    } else {
      console.error('版本太低了！！！！')
      wx.showToast({ title: '加载中', icon: 'loading' })
    }
    wx.request({
      url: baseUrl + url,
      data: param,
      method: method,
      header: {
        'apiKey': apiKey
      },
      success: (res) => {
        console.log('requestInternal: 接口请求成功[' + url + ']');
        console.log('请求数据');
        console.log(param);
        console.log('响应数据');
        console.log(res);

        if (res.data.code == 10000 || res.data.code == 10015) {
            console.log('成功')
            typeof success == "function" && success(res.data.data);
        } else if (res.data.code == 10014 || res.data.code == 10012 || res.data.code == 10002) {
            typeof success == "function" && success(res.data);
        } else {
          this.handleFail(res.data.message)
        }
      },
      fail: (res) => {
        console.log('requestInternal: 接口请求失败[' + url + ']');
        console.log(res);
        ////在这里做请求失败的统一处理
        if (typeof fail == "function") {
          fail(res)
        } else {
          this.handleFail('网络访问失败')
        }

      },
      complete: function (res) {
        //在这里做完成的统一处理
        if (wx.canIUse('showLoading')) {
          wx.hideLoading()
        } else {
          console.error('版本太低了！！！！')
        }
        typeof complete == "function" && complete(res);
      }
    })
  },
  /**Get请求方法*/
  getRequest: function (url, param, success, complete) {
    this.baseRequest(url, 'GET', param, success, null, complete)
  },
  /** Post请求方法*/
  postRequest: function (url, param, success, complete) {
    this.baseRequest(url, 'POST', param, success, null, complete)
  },
  /** Post带有fail处理的请求方法*/
  postRequestWithFail: function (url, param, success, fail, complete) {
    this.baseRequest(url, 'POST', param, success, fail, complete)
  },
  /** 请求异常处理*/
  handleFail: function (msg) {
    console.log('异常处理')
    wx.showModal({
      title: '温馨提示',
      content: '系统繁忙，请确认关闭后重试',
      showCancel: false,
      confirmText: '确认关闭',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
      fail: function (e) {
        console.log('showModal fail:')
        console.log(e)
      },
    })
  },
  onError: function (msg) {
    console.error("系统异常")
    console.error(msg)
  }
}


module.exports = request
